# -*- coding: utf-8 -*-
import frappe
from frappe.model.document import Document

class ScrapWarehouse(Document):
    """
    余料仓库控制器
    用于管理余料仓库的基本信息和状态
    """
    
    def validate(self):
        """验证余料仓库数据"""
        # 检查仓库代码是否重复
        if self.warehouse_code:
            existing_warehouse = frappe.db.exists("Scrap Warehouse", {
                "warehouse_code": self.warehouse_code,
                "name": ["!=", self.name]
            })
            if existing_warehouse:
                frappe.throw("仓库代码已存在，请使用其他代码")
        
        # 检查仓库名称是否重复
        if self.warehouse_name:
            existing_name = frappe.db.exists("Scrap Warehouse", {
                "warehouse_name": self.warehouse_name,
                "name": ["!=", self.name]
            })
            if existing_name:
                frappe.throw("仓库名称已存在，请使用其他名称")
    
    def on_update(self):
        """更新余料仓库时的处理"""
        # 更新相关库位信息
        self.update_related_locations()
    
    def on_trash(self):
        """删除余料仓库时的处理"""
        # 检查是否有关联的库位
        locations = frappe.db.get_all("Scrap Location", 
            filters={"warehouse": self.name})
        if locations:
            frappe.throw("无法删除该仓库，存在关联的库位记录")
        
        # 检查是否有关联的余料
        materials = frappe.db.get_all("Scrap Material", 
            filters={"warehouse": self.name})
        if materials:
            frappe.throw("无法删除该仓库，存在关联的余料记录")
    
    def update_related_locations(self):
        """更新关联的库位信息"""
        # 如果仓库状态变为"已取消"，则更新所有关联库位状态为"已停用"
        if self.status == "已取消":
            frappe.db.sql("""
                UPDATE `tabScrap Location`
                SET status = '已停用'
                WHERE warehouse = %s
            """, self.name)
            frappe.db.commit()
    
    def get_location_count(self):
        """获取仓库下的库位数量"""
        return frappe.db.count("Scrap Location", {"warehouse": self.name})
    
    def get_material_count(self):
        """获取仓库下的余料数量"""
        return frappe.db.count("Scrap Material", {"warehouse": self.name})